import subprocess
import time


def run_command(cmd, echo=True, check=True):
    if echo:
        print(cmd)
    cp = subprocess.run(cmd, shell=True, capture_output=True,
                        encoding="utf-8", check=check)
    return cp.stdout


def command_devices():
    devices = []
    for line in run_command("adb devices", echo=False).splitlines():
        if line.startswith("List of devices attached") or line == "":
            continue
        else:
            devices.append(line.split("\t")[0])
    return devices


def command_shellcmd(device, cmd, echo=True, check=True):
    run_command("adb -s {} shell {}".format(device, cmd),
                echo=echo, check=check)


def command_pull(device, remote, local):
    run_command("adb -s {} pull {} {}".format(device,
                remote, local), check=False)


def command_reboot(device):
    run_command("adb -s {} reboot".format(device))


def dump_timestamp(hint):
    timestamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    print("{} at {}".format(hint, timestamp))
